import time
import os
import psutil

def clear_screen():
    """清屏，兼容Linux"""
    os.system('clear')

def resource_monitor():
    """实时资源监控"""
    print("\n=== 实时系统资源监控 ===")
    while True:
        clear_screen()
        print("=" * 50)
        print("实时系统资源监控 (按 Ctrl+C 返回主菜单)")
        print("=" * 50)
        
        # CPU 使用率
        cpu_usage = psutil.cpu_percent(interval=1)
        print(f"CPU 使用率: {cpu_usage:.1f}%")
        
        # 内存使用率
        memory = psutil.virtual_memory()
        memory_usage = memory.percent
        print(f"内存使用: {memory.used / (1024**3):.1f} GB / {memory.total / (1024**3):.1f} GB ({memory_usage:.1f}%)")
        
        # 交换内存使用率
        swap = psutil.swap_memory()
        swap_usage = swap.percent
        print(f"交换内存: {swap.used / (1024**3):.1f} GB / {swap.total / (1024**3):.1f} GB ({swap_usage:.1f}%)")
        
        # 磁盘使用率（针对根分区）
        disk = psutil.disk_usage('/')
        disk_usage = disk.percent
        print(f"磁盘使用（根分区）: {disk.used / (1024**3):.1f} GB / {disk.total / (1024**3):.1f} GB ({disk_usage:.1f}%)")
        
        # 网络流量
        network_io = psutil.net_io_counters()
        print(f"网络接收: {network_io.bytes_recv / (1024**2):.1f} MB")
        print(f"网络发送: {network_io.bytes_sent / (1024**2):.1f} MB")
        
        print("\n按 Ctrl+C 返回主菜单")
        try:
            time.sleep(10)
        except KeyboardInterrupt:
            break

def disk_partitions_info():
    """显示磁盘分区信息"""
    clear_screen()
    print("=" * 50)
    print("磁盘分区信息")
    print("=" * 50)
    
    partitions = psutil.disk_partitions(all=False)
    if not partitions:
        print("未检测到磁盘分区")
    else:
        for partition in partitions:
            try:
                if 'cdrom' in partition.opts or 'removable' in partition.opts:
                    continue
                disk_usage = psutil.disk_usage(partition.mountpoint)
                if disk_usage.total == 0:
                    continue
                print(f"分区: {partition.device}")
                print(f"  挂载点: {partition.mountpoint}")
                print(f"  文件系统: {partition.fstype}")
                print(f"  已用: {disk_usage.used / (1024**3):.1f} GB / 总计: {disk_usage.total / (1024**3):.1f} GB")
                print(f"  使用率: {disk_usage.percent:.1f}%")
                print("-" * 50)
            except Exception as e:
                print(f"获取分区 {partition.device} 信息失败: {e}")
    input("\n按 Enter 返回主菜单...")

def network_stats():
    """网络流量统计"""
    clear_screen()
    print("=" * 50)
    print("网络流量统计")
    print("=" * 50)
    
    last_network_io = psutil.net_io_counters()
    print("开始统计网络流量（每2秒更新，按 Ctrl+C 返回主菜单）")
    while True:
        clear_screen()
        print("=" * 50)
        print("网络流量统计 (按 Ctrl+C 返回主菜单)")
        print("=" * 50)
        
        current_network_io = psutil.net_io_counters()
        upload_speed = (current_network_io.bytes_sent - last_network_io.bytes_sent) / (1024 * 2)  # KB/s
        download_speed = (current_network_io.bytes_recv - last_network_io.bytes_recv) / (1024 * 2)  # KB/s
        print(f"上传速率: {upload_speed:.1f} KB/s")
        print(f"下载速率: {download_speed:.1f} KB/s")
        print(f"累计接收: {current_network_io.bytes_recv / (1024**2):.1f} MB")
        print(f"累计发送: {current_network_io.bytes_sent / (1024**2):.1f} MB")
        
        last_network_io = current_network_io
        try:
            time.sleep(2)
        except KeyboardInterrupt:
            break
    input("\n按 Enter 返回主菜单...")